package com.shanghaionstar.user.service;

import android.content.Context;

import com.onstar.cn.api.UsersService;
import com.onstar.cn.common.exception.OnStarException;

import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.more.response.HeadImgRes;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.NetConnectUtil;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by Rengui Lu on 2016/7/6.
 */
public class MoreService extends BaseService<HeadImgRes> {
    private Context context;

    public MoreService(Context context) {
        this.context = context;
    }

    @Override
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public RequestEntity getRequestEntity() {
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        String idpId = ApplicationUtil.getInstance().getIdpID();
        requestEntity = service.getHeadPhoto(requestEntity, idpId);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getRequestEntity", requestEntity);
        return requestEntity;
    }

    public Observable<HeadImgRes> getHeadImg(){
        return Observable.defer(new Func0<Observable<HeadImgRes>>() {
            @Override
            public Observable<HeadImgRes> call() {
                try {
                    RequestEntity requestEntity = getRequestEntity();
                    String json = BusinessUtil.getResponse(getDatas(requestEntity), context);
                    HeadImgRes headImgRes = GsonHelper.fromJson(json,HeadImgRes.class);
                    return Observable.just(headImgRes);
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


    @Override
    public HeadImgRes jsonToBean(String json) {
        return GsonHelper.fromJson(json,HeadImgRes.class);
    }
}
